<!-- 物流线路 - 表单编辑页面 -->
<template>
  <div class="page_rela_container" >
		<div class="scroll_auto flex_cell">

    <!-- title -->
    <div class="page-content-title">
      <!-- 当前位置：新增仓储产品-->
      {{ $tt('label_current_position') }}：{{ $tt('label_pms_create_new_warehouse_product') }}
    </div>
    <el-form ref="formEl" :model="formValue" label-width="130px" class="common-form-panel-div"
      style="min-width: 1170px;">

      <ex_header_spiler :title="$tt('label_pms_product_base_info')"></ex_header_spiler>
      <el-row style="margin-top: 20px;">
        <el-col>
          <!-- 产品名称 -->
          <el-form-item :label="$tt('label_pms_product_name')">
            <el-input v-model="formValue.productName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <!-- 产品编码 -->
          <el-form-item :label="$tt('label_pms_product_code')">
            <el-input v-model="formValue.productCode"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <!-- 产品描述 -->
          <el-form-item :label="$tt('label_remark')">
            <el-input v-model="formValue.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="3">
          <!-- 关联仓库组 -->
          <el-form-item :label="$tt('label_pms_ref_warehouse_group')">
            <el-radio-group v-model="chooseWarehouseGroupId">
              <el-radio v-for="(item, index) in warehouseGroupArray" style="margin-bottom: 10px" :label="item.groupId"
                :key="item.groupId">
                {{ item.name }}
                <br v-if="index !== 0 && ((index + 1) % 5) === 0" />
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="3">
          <!-- 仓库 -->
          <el-form-item :label="$tt('label_warehouse')">
            {{ formValue.warehouses.map(e => e.warehouseName).join(' , ') }}
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <el-form-item :label="$tt('label_pms_ref_warehouse_group_setting')">
            <!-- 仓库分组配置 -->
            <el-button @click=" $router.push({ path: '/page/oms/warehouse/warehouse_group' })">{{
              $tt('label_pms_ref_warehouse_group_setting') }}</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="1">
          <!-- 仓租计算时间点 -->
          <el-form-item :label="$tt('label_pms_tenant_cal_time')">

            <div style="display: flex; gap:4px;">

              <ex_super_input v-model="formValue.timeZone" type="select" enum="TimeZoneEnum" :clearable="false">
              </ex_super_input>

              <el-time-picker v-model="formValue.timePoint" :picker-options="{
                selectableRange: '00:00:00 - 23:59:59'
              }" format="HH:mm" value-format="HH:mm" placeholder="">
              </el-time-picker>

            </div>

          </el-form-item>
        </el-col>

      </el-row>

      <!-- 产品报价信息 -->
      <!--      <ex_header_spiler :title="$tt('label_pms_product_price_cfg')"></ex_header_spiler>-->

      <!--      <el-tabs v-model="activeName" type="card" class="warehouse-product-tabs">-->
      <!--        <el-tab-pane v-for="item, index in warehouseGroupArray" v-if="item.showEditForm" :label="item.name"-->
      <!--          :name="'group_' + item.groupId" :key="'index_' + item.groupId" class="warehouse-product-tab-pane">-->
      <!--          <warehouse-price-cfg :ref="'warehouse_price_' + item.groupId" :standardServices="standardServices"-->
      <!--            :additionalServices="additionalServices" :priceUnitMap="priceUnitMap" :inputForm="item"></warehouse-price-cfg>-->
      <!--        </el-tab-pane>-->

      <!--      </el-tabs>-->

      <!-- 产品报价信息 -->
      <ex_header_spiler title="标准价卡"></ex_header_spiler>
      <div style="position: relative;">

        <!-- 添加价卡版本 -->
        <el-button @click="adTabConfig" style="position: absolute;  top: -32px; right: 20px; z-index: 999; "
          icon="el-icon-plus">添加价卡版本</el-button>

        <ex-button-delete style="position: absolute;  top: 60px; left: 420px; z-index: 999; "
          v-if="formValue.standardPriceVersions && formValue.standardPriceVersions.length > 0 && activeName != getTabId(formValue.standardPriceVersions[0])"
          message="确定删除当前产品价卡配置？" label="删除当前配置" byAction :delAction="() => {
            formValue.standardPriceVersions = formValue.standardPriceVersions.filter(tab => getTabId(tab) != activeName);
            activeName = getTabId(formValue.standardPriceVersions[0]);
          }"></ex-button-delete>

        <el-tabs v-if="formValue.standardPriceVersions && formValue.standardPriceVersions.length > 0" v-model="activeName"
          type="card">
          <el-tab-pane v-for="(item, index) in formValue.standardPriceVersions" :label="getTabTitle(item)"
            :name="getTabId(item)" :key="item.tabId">
            <warehouse-price-cfg ref="warehouse_price_cfg" :versionStartTimeDisabled="index === 0"
              :priceVersionId="item.id" :standardServices="standardServices" :additionalServices="additionalServices"
              :priceUnitMap="priceUnitMap" :inputForm="item">

            </warehouse-price-cfg>
          </el-tab-pane>
        </el-tabs>

        <div v-else style="padding-left: 100px; display: flex; align-items: center;  color: #d41515; ">
          <i class="el-icon-warning" style="margin-right: 8px;"></i>
          还没添加价卡版本
        </div>

      </div>

    </el-form>


	</div>

<div class="page_rela_bottom_area"  >
      <!-- 保存 -->
      <el-button type="primary" @click="submitForm()">{{ $tt('label_save') }}</el-button>
      <!-- 取消 -->
      <el-button @click="return_page_back()">{{ $tt('label_cancel') }}</el-button>
    </div>

  </div>
</template>
<script>
import router_params from '@/mixin/router_params';

import WarehouseGroup from '@/component/pms/warehouse-group.vue'
import WarehousePriceCfg from '@/component/pms/warehouse_price_cfg.vue'


export default {
  // title: "新增" + moduleName,
  components: { WarehouseGroup, WarehousePriceCfg },
  mixins: [router_params],
  data() {

    return {
      edit: false,
      "operateType": "",
      "chooseWarehouseGroupIds": [],
      "chooseWarehouseGroupId": '',
      "formValue": {
         remark:"",
        "refWarehouse": [],
        "timeZone": "BEIJING",
        "timePoint": "00:00:00",
        "standardPriceVersions": [],
        "warehouses": []
      },
      "activeName": "",
      "groupId": '',

      "warehouseGroupCache": {},
      "warehouseGroupArray": [],

      // 服务项
      "standardServices": [],
      "additionalServices": [],
      "priceUnitMap": {},

      "initWarehouseGroupDone": false,
      "loadEditFormDone": false,
      "defaultServiceLoadDone": false,

      "editFormData": {}

    };
  },

  created() {



    this.initWarehouseGroup()
    this.iniDefaultConfigs()

    if (this.formValue.standardPriceVersions && this.formValue.standardPriceVersions.length > 0) {
      this.activeName = this.getTabId(this.formValueCache.standardPriceVersions[0])
    }

  },

  mounted() {
  },

  watch: {
    'chooseWarehouseGroupId'(val, old) {
      let _this = this
      if (val) {
        this.formValue.warehouses = _this.warehouseGroupCache[val].warehouses
      }
    },
    'chooseWarehouseGroupIds'(val, old) {

      let _this = this

      if (!val || val.length == 0) {

        for (let kk in _this.warehouseGroupCache) {
          _this.warehouseGroupCache[kk].showEditForm = false
        }

        return
      }


      val.forEach(e => {
        if (_this.warehouseGroupCache[e]) {
          _this.warehouseGroupCache[e].showEditForm = true
        }
      })

      let leftWhIds = _this.warehouseGroupArray.filter(e => !val.contains(e.groupId)).map(e => e.groupId)

      if (leftWhIds && leftWhIds.length > 0) {
        leftWhIds.forEach(e => {
          if (_this.warehouseGroupCache[e]) {
            _this.warehouseGroupCache[e].showEditForm = false
          }
        })
      }

      if (val && val.length > 0) {
        _this.chooseWarehouseGroupId = val[0]

        this.formValue.warehouses = _this.warehouseGroupCache[_this.chooseWarehouseGroupId].warehouses
      }
    }
  },

  methods: {
    adTabConfig() {

      let sample = {}

      if (this.chooseWarehouseGroupId === undefined || this.chooseWarehouseGroupId === '' || this.formValue.warehouses.length <= 0) {
        this.$message({
          showClose: true,
          message: '请先关联仓库组',
          type: 'warning'
        })
        return
      }

      if (this.formValue.standardPriceVersions && this.formValue.standardPriceVersions.length > 0) {
        sample = JSON.parse(JSON.stringify(this.formValue.standardPriceVersions[this.formValue.standardPriceVersions.length - 1]))
        let lastTime = sample.versionEndTime
        sample.versionStartTime = parseInt(lastTime) + 86400000
        sample.versionEndTime = parseInt(lastTime) + 31536000000
        sample.tabId = 'id_' + (Math.random() + '').replace('.', '')
        sample.warehouses = this.formValue.warehouses
        sample.id = ''
      } else {
        // init 价卡

        if (this.warehouseGroupCache[this.chooseWarehouseGroupId]) {
          let wl = this.warehouseGroupCache[this.chooseWarehouseGroupId]

          let lastTime = new Date().getTime()

          sample.tabId = 'id_' + (Math.random() + '').replace('.', '')
          sample.daterange = [lastTime, parseInt(lastTime) + 31536000000]
          sample.versionId = '-1'
          sample.versionName = ''
          sample.versionStartTime = lastTime
          sample.versionEndTime = parseInt(lastTime) + 31536000000
          sample.versionType = ''
          sample.status = 'ENABLE'
          sample.versionTag = ''
          sample.productId = ''
          sample.warehouses = this.formValue.warehouses
          sample.id = ''
        }

      }

      this.formValue.standardPriceVersions.push(sample)

      this.activeName = this.getTabId(sample)
    },

    getTabTitle(item) {
      return this.$dateFormatDate(item.versionStartTime) + ' 至 ' + this.$dateFormatDate(item.versionEndTime)
    },

    getTabId(item) {
      return 'tab_' + item.tabId
    },

    // 加载仓库分组信息
    initWarehouseGroup() {
      let _this = this
      this.$ajax({
        url: '/fms-api/product/PmsWarehouseGroupRpc/selectAll.json',
        success: (res) => {

          let tmpArr = res.data.rows

          _this.warehouseGroupCache = {}

          for (let i = 0; i < tmpArr.length; i++) {

            tmpArr[i].groupId = 'group_' + i
            tmpArr[i].showEditForm = false


            _this.warehouseGroupCache[tmpArr[i].groupId] = tmpArr[i]
          }

          _this.warehouseGroupArray = tmpArr
          _this.initWarehouseGroupDone = true

          _this.loadEditFormDataByParams()

        }
      });
    },
    init_data_default(into_params) {
      this.edit = !!into_params.edit
      if (this.edit) {
        if (into_params.id) {
          this.loading = true
          this.$ajax({
            url: "/fms-api/product/PmsWarehouseProductRpc/detail.json",
            method: 'post',
            data: { id: into_params.id },
            success: (res) => {
              if (res && res.data) {
                this.editFormData = res.data
              }

              this.loadEditFormDone = true
              this.loadEditFormDataByParams()
              this.$emit("tagModifyLabel", { _key: 'label_name_code', name: "修改仓储产品", code: res.data.productName })

            }
          })
        }
        this.$emit("tagModifyLabel", "修改仓储产品")
      } else {
        this.$emit("tagModifyLabel", "新增仓储产品")
      }
    },
    // 获取编辑信息
    loadEditFormByParam() {
      let _this = this
      let editId = this.$route.query.id;
      if (editId) {
        _this.$ajax({
          url: '/fms-api/product/PmsWarehouseProductRpc/detail.json?id=' + editId,
          success: (res) => {
            if (res && res.data) {
              _this.editFormData = res.data
            }

            _this.loadEditFormDone = true
            _this.loadEditFormDataByParams()
            this.$emit("tagModifyLabel", { _key: 'label_name_code', name: "修改仓储产品", code: res.data.productName })

          }
        });
        this.$emit('tagModifyLabel', "修改仓储产品")
      } else {
        this.$emit('tagModifyLabel', "新增仓储产品")
      }
    },

    // 初始化编辑表单
    loadEditFormDataByParams() {

      let _this = this
      if (_this.initWarehouseGroupDone && _this.loadEditFormDone && _this.defaultServiceLoadDone) {

        let tmp = _this.editFormData
        let chooseWarehouseGroupIds = []
        if (tmp.warehouseGroups) {
          chooseWarehouseGroupIds = tmp.warehouseGroups.map(g => g.groupId)
        }

        console.log(chooseWarehouseGroupIds)
        _this.chooseWarehouseGroupIds = chooseWarehouseGroupIds
        let chooseWarehouseGroupId = _this.chooseWarehouseGroupIds[0]
        let currentWarehouses = []

        _this.warehouseGroupArray.forEach(row => {
          for (let i = 0; i < tmp.warehouseGroups.length; i++) {

            if (chooseWarehouseGroupId === row.groupId) {
              currentWarehouses = row.warehouses
            }

            let formRow = tmp.warehouseGroups[i]
            if (row.groupId == formRow.groupId) {
              for (let kk in formRow) {
                if (kk == 'warehouses') {
                  continue
                }
                row[kk] = formRow[kk]
              }
              break
            }
          }
          row.warehouses = _this.warehouseGroupCache[row.groupId].warehouses
        })

        tmp.warehouses = currentWarehouses
        _this.formValue = tmp
      }

      // 对数组内复制的对象进行处理，赋值 tabId
      if (_this.formValue.standardPriceVersions && _this.formValue.standardPriceVersions.length > 0) {

        _this.formValue.standardPriceVersions.forEach(e => {
          e.tabId = 'id_' + (Math.random() + '').replace('.', '')
          e.warehouses = _this.formValue.warehouses

          if (e.warehouseGroupPriceVersion) {
            e.groupId = e.warehouseGroupPriceVersion[0].groupId
          }
        })
        this.activeName = this.getTabId(_this.formValue.standardPriceVersions[0])

      }
    },


    // 加载默认常量信息
    iniDefaultConfigs() {
      let _this = this
      this.$ajax({
        url: '/fms-api/product/PmsWarehouseProductRpc/getDefaultServiceForms.json',
        success: (res) => {
          _this.standardServices = res.data.standard
          _this.additionalServices = res.data.additional

          _this.defaultServiceLoadDone = true
          _this.loadEditFormDataByParams()
        }
      });

      _this.$ajax({
        url: '/fms-api/product/PriceUnitRpc/getPriceUnitMap.json',
        success: (res) => {
          if (res && res.data) {
            _this.priceUnitMap = res.data
          }
        }
      });
    },


    // 提交表单
    submitForm() {

      let _this = this

      this['$refs']['formEl'].validate((valid) => {

        // 公共属性 groupId, groupName, warehouses

        var wel = _this.warehouseGroupCache[_this.chooseWarehouseGroupId];

        // 补充标准价卡数据
        if (_this.formValue.standardPriceVersions && _this.formValue.standardPriceVersions.length > 0) {
          let standardPriceVersions = _this.$refs['warehouse_price_cfg'].map(e => e.getWarehouseFormData())

          if (!_.isEmpty(standardPriceVersions)) {
            for (let i = 0; i < standardPriceVersions.length; i++) {
              var standardPriceVersion = standardPriceVersions[i];
              var warehouseGroupPriceVersion = standardPriceVersion.warehouseGroupPriceVersion;
              warehouseGroupPriceVersion.forEach(e => {
                e.warehouses = _this.formValue.warehouses
                e.groupId = wel.groupId
                e.groupName = wel.name
              })
            }
          }

          this.formValue.standardPriceVersions = standardPriceVersions
        }


        if (_.isEmpty(this.formValue.standardPriceVersions)) {
          this.$message({
            showClose: true,
            message: '请添加价卡版本',
            type: 'warning'
          })
          return
        }

        console.log(this.formValue)
        let tmpData = _this.formValue

        if (valid) {
          this.$ajax({
            url: '/fms-api/product/PmsWarehouseProductRpc/saveUpdate.json',
            type: 'json',
            data: tmpData,
            success: (responseData) => {

              this.$message({
                showClose: true,
                message: '提交成功',
                type: 'success'
              })
              this.return_emit(null, "reload")
              this.return_page_back()
            }
          });

        } else {
          return false
        }
      });
    },




  }
};

</script>
<style>
.product-line-limit-div,
.product-line-limit-div-2 {
  display: flex;
}


.product-line-limit-div .product-line-limit-col {
  width: 220px;
  text-align: center;
  margin-right: 10px;
}

.product-line-limit-div-2 div {
  width: 300px;
  /*text-align: center;*/
  margin-right: 10px;
}

.price-cal-div-row {
  display: flex;
}

.price-cal-div-row .price-cal-col {
  width: 120px;
  text-align: center;
}

.price-cal-div-row div {
  margin-right: 8px;
  text-align: center;
}
</style>
